package com.jerry.project;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

public class getCommentServlet extends HttpServlet {
	@Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
		JSONObject jsonobj=null;
		String id=null;
		
		try {
			jsonobj=new JSONObject(reqToJSONString.reqToJSONString(req));
			if(jsonobj.has("id")){
				id=jsonobj.getString("id");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	    Key commentKey = KeyFactory.createKey("CommentKind", "comment");
	    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    if(id!=null){
        	Filter queryFilter =FilterOperator.EQUAL.of("id", id);
        	Query query = new Query("Comment", commentKey).setFilter(queryFilter);
        	List<Entity> comments = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(100));
        	if(comments.size()!=0){
        		for(Entity e:comments){
            		e.removeProperty("id");
            	}
            	Sort.sortbyWhat(comments, "createTime",-1);
            	resp.getWriter().write(ToJSON.ListToJSON(comments,"comments"));
        	}
        	if(comments.size()==0){
        		resp.getWriter().write("0");
        	}
	    }
	}
}
